package com.example.dianproject.service;

import com.example.dianproject.entity.SysUser;
import com.example.dianproject.repository.SysUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Slf4j
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final SysUserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("加载用户信息: {}", username);
        
        SysUser user = userRepository.findByUsername(username)
            .orElseThrow(() -> {
                log.debug("用户不存在: {}", username);
                return new UsernameNotFoundException("用户不存在: " + username);
            });

        log.debug("用户信息加载成功: {}", username);
        return new User(
            user.getUsername(),
            user.getPassword(),  // 使用明文密码
            Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getRole().name()))
        );
    }
} 